﻿using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using DataLoader.Common.Config;
using DataLoader.UI.ViewModels;
using Microsoft.Practices.Unity;

namespace DataLoader.UI.Views
{
    public partial class MainView : Window
    {
        public MainViewModel MainViewModel { get; private set; }

        public MainView([Dependency] MainViewModel mainViewModel)
        {
            InitializeComponent();
            MainViewModel = mainViewModel;
            DataContext = MainViewModel;
            ConfigDataGrid.CellEditEnding += ConfigDataGrid_CellEditEnding;
        }


        void ConfigDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            DataGridRow row = e.Row as DataGridRow;

            if (row != null && ((IConfigItem) row.Item).IsDirty)
            {
                if (e.EditAction == DataGridEditAction.Commit)
                    MainViewModel.IsDirty = true;

                DataGridCell cell = GetCell(row, e.Column.DisplayIndex);
                if (cell != null)
                    cell.Foreground = Brushes.Red;
            }

        }

        public DataGridCell GetCell(DataGridRow row, int colIndex)
        {
            DataGridCellsPresenter p = GetVisualChild<DataGridCellsPresenter>(row);
            DataGridCell cell = p.ItemContainerGenerator.ContainerFromIndex(colIndex) as DataGridCell;
            return cell;
        }


        static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T;

                if (child == null)
                    child = GetVisualChild<T>(v);
                if (child != null)
                    break;

            }
            return child;
        } 
    }
}